package cn.wolfcode.wolf2w.gateway.filter;

import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.common.redis.service.RedisService;
import cn.wolfcode.wolf2w.common.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author 浪兎兎
 * @since 2025-06-18 11:37
 */
@Component
public class AntiReflushFilter implements GlobalFilter {

    @Autowired
    private RedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String ip = request.getRemoteAddress().getAddress().toString();
        String path = request.getURI().getPath();
        String key = RedisKeys.ANIT_REFLUSH.join(path, ip);
        redisService.setnxCacheObject(key, 0, RedisKeys.ANIT_REFLUSH.getTtl(), TimeUnit.SECONDS);
        Long count = redisService.incrementCacheObjectValue(key, 1);
        if (count > 20) {
            // 削他
            String jsonString = JSON.toJSONString(R.fail(500, "你已被禁止访问该接口1分钟：请勿频繁刷新"));
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
            DataBuffer wrap = response.bufferFactory().wrap(jsonString.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }
}
